package com.yuqian.JavaSe.leetcode.easy;

/**
 * Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.


将一个链表每每两个交换，不能改变链表的值，只能改变节点的位置
 * @author yuqian
 *
 */
public class SwapNodesinPairs {
	public static ListNode swapPairs(ListNode head) {
		if(head==null||head.next==null){
            return head;
        }
		ListNode result =head.next;
        ListNode temp =head.next.next;
        head.next.next = head;
        head.next =temp;
        head = temp;
        result.next.next=swapPairs(head);
        return result;
    }
	
	public static void main(String[] args) {
		ListNode n1 = new ListNode(1);
		ListNode n2 = new ListNode(2);
		ListNode n3 = new ListNode(3);
		ListNode n4= new ListNode(4);
		n1.next = n2;
		n2.next = n3;
		n3.next = n4;
		ListNode result = swapPairs(n1);
		while(result.next!=null)
		{
			System.out.print(result.val+"  ");
			result = result.next;
		}
		System.out.print(result.val+"  ");
	}
}
